import {
	QueryDeviceEvent,
} from "@/api/elder/alarm/index.js";
import constant from '@/utils/constant';
import storage from '@/utils/storage';
import Vue from "vue";

const state = {
	deviceEvents: [], //全部报警
	readEvents: storage.get(constant.readEvents)||{},
	intervalId: null, // 定时器ID
}

const mutations = {
	SET_DEVICE_EVENTS:(state, events)=> {
		state.deviceEvents = events
	},
	SET_READEVENTS: (state, id) => {
		if(state.readEvents[id]){
			state.readEvents[id] = new Date().getTime();
		}
		else{
			Vue.set(state.readEvents, id, new Date().getTime());
		}
		storage.set(constant.readEvents, state.readEvents)
	},
	SET_INTERVAL_ID: (state, id) => {
		state.intervalId = id;
	},
}

const actions = {
	async fetchDeviceEvents({
		commit,
		state,
		rootState
	}) {
		// 清除旧的定时器
		if (state.intervalId) {
			clearInterval(state.intervalId);
		}
		const response = await QueryDeviceEvent();
		let events = [];
		if (response.code == 200) {
			response.rows.forEach(event => {
				// events[event.id] = event;
				events.push(event);
			});
		}
		if(rootState.user.name=='admin'){
			commit('SET_DEVICE_EVENTS', events);
		}
		else{
			commit('SET_DEVICE_EVENTS', events.filter(i=>i.身份证号==rootState.user.name));
		}
		// 设置新的定时器
		const intervalId = setInterval(() => {
			this.dispatch('fetchDeviceEvents');
		}, 30000); // 每30秒执行一次
		commit('SET_INTERVAL_ID', intervalId);
	},
	addReadEvents({
		commit,
		state
	}, id) {
		commit('SET_READEVENTS', id);
	},
}

const getters = {
	//通过deviceEventsWithIsRead中isRead=false的报警数量
	noReadCount: (state, getters) => {
		let events = getters.deviceEventsWithIsRead;
		let count = 0;
		for (let item of events) {
			if (!item.isRead) {
				count++;
			}
		}
		return count;
	},
	//将deviceEvents中没有在readEvents中的报警，添加属性isRead=false,有的话添加属性isRead=true
	deviceEventsWithIsRead: (state) => {
		let events = state.deviceEvents;
		for (let item of events) {
			if (!state.readEvents[item.id]) {
				// Vue.set(item, isRead, false);
				item.isRead=false
			} else {
				// Vue.set(item, isRead, true);
				item.isRead=true
			}
		}
		return events;
	},
}

export default {
	state,
	mutations,
	actions,
	getters
}
